/* 
 * File:   main.cpp
 * Author: Tung Mai
 *
 * Created on April 6, 2010, 2:38 PM
 */

#include <Carbon/Carbon.h>
#include <stdlib.h>
#include <iostream>

using namespace std;

static OSStatus appChanged(EventHandlerCallRef nextHandler, EventRef anEvent, void* userData)
{
    ProcessSerialNumber psn;
    GetEventParameter(anEvent, kEventParamProcessID, typeProcessSerialNumber,
                      NULL, sizeof(psn), NULL, &psn);

    // Determine process name
    char procName[255];
    {
        ProcessInfoRec pInfo;
        Str255 procName255;
        FSSpec ref;

        pInfo.processInfoLength = sizeof(ProcessInfoRec);
        pInfo.processName = procName255;
        pInfo.processAppSpec = &ref;
        GetProcessInformation(&psn, &pInfo);

//        cout << "Result: " << pInfo.processName << endl;
        const unsigned int size = (unsigned int)procName255[0];
        cout << "Size: " << size << endl;
        memcpy(procName, procName255 + 1, size);
        procName[size] = '\0';
        cout << "procName: " << procName << endl;
    }

    if(strcmp(procName, "ScreenSaverEngine") == 0)
    {
        cout << "SS started\n";
        printf("Found %s\n", procName);
    }
    else
    {
        cout << "SS stopped\n";
    }

    return noErr;
}

int main(int argc, char** argv) {
    EventTypeSpec es = {kEventClassApplication, kEventAppFrontSwitched};
//    es[0].eventClass = kEventClassApplication;
//    es[0].eventKind = kEventAppFrontSwitched;
    InstallApplicationEventHandler(NewEventHandlerUPP(appChanged), GetEventTypeCount(es), &es, NULL, NULL);
    RunApplicationEventLoop();


    return (EXIT_SUCCESS);
}

//void myCallbackFntn(CFNotificationCenterRef center, void *observer, CFStringRef notificationName,
//                    const void *observedObject, CFDictionaryRef userInfo)
//{
//    printf("My Callback is called\n");
//}
//
//int main(int argc, char** argv) {
//    IONotificationPortRef  notifyPortRef;
//    void *observer;
//    CFStringRef observedObject = CFSTR("com.apple.screensaver.didstop");
//    CFNotificationCenterRef center = CFNotificationCenterGetDistributedCenter();
//    CFNotificationCenterAddObserver(center, observer, myCallbackFntn, CFSTR("My Notification"),
//                                    observedObject, CFNotificationSuspensionBehaviorDeliverImmediately);
//
////    CFRunLoopAddSource( CFRunLoopGetCurrent(),
////            IONotificationPortGetRunLoopSource(notifyPortRef), kCFRunLoopCommonModes );
//
//    CFRunLoopRun();
//
//    return (EXIT_SUCCESS);
//}

